import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:wayofdressing/dio/UserDio.dart'; // 假设这是处理用户相关API请求的文件
import 'package:wayofdressing/dio/configureDio.dart'; // 假设这是配置Dio实例的文件
import 'package:wayofdressing/good_method/show_dialog.dart';
import 'package:wayofdressing/main_navigator_widget.dart'; // 假设这是登录成功后跳转的页面
import 'package:wayofdressing/contraints.dart';
import 'package:wayofdressing/good_method/show_dialog.dart';

class LoginScreen extends StatefulWidget {
  static const id = 'LoginScreen';

  const LoginScreen({Key? key}) : super(key: key);

  @override
  State<LoginScreen> createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  final TextEditingController _loginAccountController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadSavedCredentials(); // 加载保存的用户名和密码
  }

  void _loadSavedCredentials() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? savedAccount = prefs.getString('account');
    String? savedPassword = prefs.getString('password');

    if (savedAccount != null && savedAccount.isNotEmpty) {
      _loginAccountController.text = savedAccount;
    }
    if (savedPassword != null && savedPassword.isNotEmpty) {
      _passwordController.text = savedPassword;
    }
  }

  @override
  void dispose() {
    _loginAccountController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  void _login() async {
    if (_formKey.currentState!.validate()) {
      // 表单验证通过
      String loginAccount = _loginAccountController.text.trim();
      String password = _passwordController.text.trim();
      try {
        Response<dynamic> response = await getUserByAccount(loginAccount, dio);
        dynamic responseData = response.data;
        print('Response Data: $responseData');

        if (responseData != null && responseData['success'] == true) {
          dynamic userData = responseData['data'];
          print('User Data: $userData');

          // 验证密码是否匹配
          if (userData != null && userData['password'] == password) {
            // 密码匹配，保存到SharedPreferences
            await saveUserData(userData['name'], password,userData['id'],loginAccount??'');
            // 导航到主页或者其他页面
            Navigator.pushNamed(context, MainNavigatorWidget.id);
          } else {
            ShowDialog.showErrorAndDetail(context,'登录失败，用户名或密码错误');
          }
        } else {
          String errorMsg = responseData['errorMsg'] ?? '未知错误';
          print('Failed to find user: $errorMsg');
          ShowDialog.showErrorAndDetail(context,'登录失败，$errorMsg');
        }
      } catch (e) {
        print('Error: $e');
        ShowDialog.showErrorAndDetail(context,'登录失败，发生未知错误');
      }
    }
  }

  Future<void> saveUserData(String username, String password,int id,String account) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setString('username', username);
    await prefs.setString('password', password);
    await prefs.setInt('id', id);
    await prefs.setString('account',account);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        toolbarHeight: 80,
        leadingWidth: 100,
        centerTitle: true,
        title: const Text(
          '登录',
          style: TextStyle(
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontSize: kTopTitleFontSize,
          ),
        ),
        leading: Row(
          children: [
            const SizedBox(
              width: 10,
            ),
            GestureDetector(
              onTap: () {
                Navigator.pop(context);
              },
              child: Transform.scale(
                scaleX: -1,
                child: Icon(
                  Icons.play_arrow_rounded,
                  size: kAppBarButtonSize,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
          ],
        ),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 32.0),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Flexible(
                child: Hero(
                  tag: 'logo',
                  child: Container(
                    child: Image.asset(
                      'images/peanutB.png',
                      width: 120,
                      height: 120,
                    ),
                  ),
                ),
              ),
              SizedBox(height: 20,),
              TextFormField(
                controller: _loginAccountController,
                decoration: InputDecoration(
                  labelText: '账号',
                  labelStyle: TextStyle(fontSize: 20, color: Colors.grey),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.0),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    borderSide: BorderSide(width: 2, color: Colors.grey),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    borderSide: BorderSide(width: 2, color: Colors.black),
                  ),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入账号';
                  }
                  return null;
                },
              ),
              SizedBox(height: 10),
              TextFormField(
                controller: _passwordController,
                obscureText: true,
                decoration: InputDecoration(
                  labelText: '密码',
                  labelStyle: TextStyle(fontSize: 20, color: Colors.grey),
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.0),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    borderSide: BorderSide(width: 2, color: Colors.grey),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(25.0),
                    borderSide: BorderSide(width: 2, color: Colors.black),
                  ),
                ),
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  return null;
                },
              ),
              SizedBox(height: 40),
              Container(
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(25),
                  border: Border.all(
                    color: Colors.black54,
                    width: 2,
                  ),
                ),
                child: TextButton(
                  child: Text(
                    '登录',
                    style: TextStyle(color: Colors.black54, fontSize: 30),
                  ),
                  onPressed: _login,
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
